﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VideoClipNameHelper;

namespace AddYearToClip
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ConfigPaths cp = new ConfigPaths();
        List<VideoFile> sourceVideoFiles;//=new List<VideoFile>();
        List<string> errList = new List<string>();
        int nErrors = 0;

        public MainWindow()
        {
            InitializeComponent();
            //
            VideoClipNameHelper.ConfigData.ReadConfig(cp);
            btnDo.IsEnabled = false;
            btnDo.Content = "...";
            //
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            nErrors += VideoClipNameHelper.VideoFile.LoadClipsFromDisk(cp.SourceDirs, ref sourceVideoFiles, errList);
            for(int i= sourceVideoFiles.Count()-1; i>=0; i--)
            {
                if (VideoClipData.UndefinedYear != sourceVideoFiles[i].vcd.Year)
                {
                    sourceVideoFiles.RemoveAt(i);
                }
            }
            //
            btnDo.Content = "Ok";
            btnDo.IsEnabled = true;
            //
            lblStartIndex.Content = ">" + Properties.Settings.Default.StartIndex.ToString();
            //
        }

        private async void btnDo_Click(object sender, RoutedEventArgs e)
        {
            btnDo.IsEnabled = false;
            btnDo.Content = "Doing";
            //
            List<string> ls = new List<string>();
            int i = 0;
            //
            try
            {
                //
                int kount = 0;
                i = Properties.Settings.Default.StartIndex;
                lblStartIndex.Content = "<"+i.ToString();
                for (; i< sourceVideoFiles.Count();i++)
                //foreach (VideoFile vf in sourceVideoFiles)
                {
                    lblCount.Content = kount.ToString();
                    if (kount > 200)
                    {
                        break;
                    }
                    if (VideoClipData.UndefinedYear != sourceVideoFiles[i].vcd.Year) continue;
                    //
                    string search = sourceVideoFiles[i].vcd.Artist + " - " + sourceVideoFiles[i].vcd.Title;
                    int year = await getYear(search);
                    if (VideoClipData.UndefinedYear != year)
                    {
                        //
                        addYearToFileName(sourceVideoFiles[i].PathName, year);
                        //
                        lblInfo.Content = sourceVideoFiles[i].FileNameWithoutExtension();
                        ls.Add($"{sourceVideoFiles[i].FileNameWithoutExtension()}\t{year}");
                        kount++;
                    }
                }
                //
                
                //
            }
            catch(Exception ex)
            {
                MessageBox.Show($"{ex.Message}+{ex.StackTrace}", $"{ex.Source}");
            }
            finally
            {
                Properties.Settings.Default.StartIndex = i;
                Properties.Settings.Default.Save();
                //
                System.IO.File.WriteAllLines($"__addyear{DateTime.Now.Day}.txt", ls);
                //
                Application.Current.Shutdown(0);
            }
            //
            btnDo.Content = "Ok";
            btnDo.IsEnabled = true;
        }

        private void addYearToFileName(string pathname, int year)
        {
            int lParen = pathname.LastIndexOf('[');
            if(lParen >=0)
            {
                string leftPart = pathname.Substring(0, lParen);
                string rightpart = pathname.Substring(lParen);
                //
                string lP = System.IO.Path.GetFileNameWithoutExtension(leftPart);
                string rP = System.IO.Path.GetFileNameWithoutExtension(rightpart);
                //
                string newName = $"{leftPart}({year}){rightpart}";
                //
                System.IO.File.Move(pathname, newName);
            }
        }

        private async Task<int> getYear(string searchdata)
        {
            int year = VideoClipData.UndefinedYear;
            string url = "https://www.google.com/search?q=";
            //https://www.google.pl/?gfe_rd=cr&ei=8i-vWPDhOcni8AfqqaTADQ#q=Corona+-+Rhythm+Of+The+Night&*
            //url += Uri.EscapeUriString("Corona - Rhythm Of The Night");
            url += Uri.EscapeUriString(searchdata);
            //
            await Task.Delay(2000 + (DateTime.Now.Millisecond / 2)).ConfigureAwait(false);
            //
            string s = await getPage(url);
            //
            //await copyTextToClipboard(s);
            //await Task.Run(() => System.IO.File.WriteAllText("..\\dumppage.txt", s));

            Regex r;
            Match m;
            //
            string artist = "";
            string album = "";
            string released = "";
            string genre = "";
            //
            {
                string pattern = "<div class=\"_o0d\"><span class=\"_gS\">Wykonawca: </span><span class=\"_tA\"><a class=\"_tA fl\" href=\".*\">(.*)</a></span></div>";
                r = new Regex(pattern, RegexOptions.IgnoreCase);
                m = r.Match(s);
                if (m.Success)
                {
                    artist = m.Groups[1].Value;
                }

            }
            {
                string pattern = "<div class=\"_o0d\"><span class=\"_gS\">Album: </span><span class=\"_tA\"><a class=\"_tA fl\" href=\".*\">(.*)</a></span></div>";
                r = new Regex(pattern, RegexOptions.IgnoreCase);
                m = r.Match(s);
                if (m.Success)
                {
                    album = m.Groups[1].Value;
                }
            }
            {
                string pattern = "<div class=\"_o0d\"><span class=\"_gS\">Data wydania: </span><span class=\"_tA\">(\\d\\d\\d\\d)</span></div>";
                r = new Regex(pattern, RegexOptions.IgnoreCase);
                m = r.Match(s);
                if (m.Success)
                {
                    released = m.Groups[1].Value;
                }
            }
            {
                // albo gatunki...
                string pattern = "<div class=\"_o0d\"><span class=\"_gS\">Gatunek: </span><span class=\"_tA\">(.*)</span></div>";
                r = new Regex(pattern, RegexOptions.IgnoreCase);
                m = r.Match(s);
                if (m.Success)
                {
                    genre = m.Groups[1].Value;
                }
            }
            //
            //if ("" != artist && "" != album && "" != released && "" != genre)
            if ("" != artist && "" != album && "" != released)
            {
                year = int.Parse(released);
                if(year<1900 || year > DateTime.Now.Year)
                {
                    year = VideoClipData.UndefinedYear;
                }
            }
            //
            return year;
        }

        private async Task<string> getPage(string url)
        {
            using (HttpClient client = new HttpClient())
            using (HttpResponseMessage response = await client.GetAsync(url))
            using (HttpContent content = response.Content)
            {
                byte[] bresult = await content.ReadAsByteArrayAsync();
                var contentType = content.Headers.ContentType;
                if(null == contentType)
                {
                    throw new Exception("HTTP response bad");
                }
                //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Encoding enc = Encoding.GetEncoding(contentType.CharSet);
                string result = enc.GetString(bresult);
                //ContentRange: null
                //ContentType: { text / html; charset = ISO-8859-2}
                if (result != null)
                {
                    return Uri.UnescapeDataString(result);
                }
            }
            return "";
        }

        private void btnResetCounter_Click(object sender, RoutedEventArgs e)
        {
            e.Handled = true;
            //
            Properties.Settings.Default.StartIndex = 0;
            Properties.Settings.Default.Save();
        }
        //===================================================================
        private bool isEndsWithYear(string fn)
        {
            int k = fn.Length;
            //
            if (k < 6) return false;
            //
            return
            '(' == fn[k - 6] &&
            ('1' == fn[k - 5] || '2' == fn[k - 5]) &&
            Char.IsDigit(fn[k - 4]) &&
            Char.IsDigit(fn[k - 3]) &&
            Char.IsDigit(fn[k - 2]) &&
            ')' == fn[k - 1]
            ;
        }
        private class OldNew
        {
            public string Old;
            public string New;
        }
        private List<OldNew> lon = new List<OldNew>();
        private void btnUpdateDb_Click(object sender, RoutedEventArgs e)
        {
            sourceVideoFiles.Clear();
            VideoClipNameHelper.VideoFile.LoadClipsFromDisk(cp.SourceDirs, ref sourceVideoFiles, errList);
            /*
context.Database.Connection
{System.Data.SqlServerCe.SqlCeConnection}
    CanRaiseEvents: true
    ConnectionString: "Data Source=Stats.sdf"
    ConnectionTimeout: 0
    Container: null
    DataSource: "Stats.sdf"
    Database: "Stats.sdf"
    DatabaseIdentifier: "99f039ff-282a-4563-932e-f5cb570905b6"
    DbProviderFactory: {System.Data.SqlServerCe.SqlCeProviderFactory}
    DesignMode: false
    Events: {System.ComponentModel.EventHandlerList}
    ServerVersion: "4.0.8876.1"
    Site: null
    State: Open
             
             
             */
            //
            int nn = 0;
            //CDBHandler.DumpDb("@DumpDb.txt");
            CDBHandler.ScanData(callback);
            //
            foreach (var on in lon)
            {
                string Old = on.Old;
                //int k = on.Old.Length;
                if (isEndsWithYear(Old)) continue;
                //
                string concatShortName = VideoClipData.GetNameWithoutResolution(on.Old);
                //VideoFile vfDisk = (from y in sourceVideoFiles where (VideoClipData.GetNameWithoutResolution(y.FileNameWithoutExtension())).StartsWith(Old) select y).FirstOrDefault();
                VideoFile vfDisk = (from y in sourceVideoFiles where y.FileNameWithoutExtension().StartsWith(Old) select y).FirstOrDefault();
                //
                if (null == vfDisk)
                {
                    CDBHandler.DeleteRecord(Old);
                }
                else
                {
                    string fnWithoutResolution = VideoClipData.GetNameWithoutResolution(vfDisk.FileName());
                    string fnDisk = VideoClipData.GetNameWithoutResolution(vfDisk.FileNameWithoutExtension());
                    if(isEndsWithYear(fnDisk))
                    {
                        //string path = System.IO.Path.GetDirectoryName(vfDisk.PathName);
                        CDBHandler.UpdateClipName(Old, fnDisk);
                    }
                }
                //
            }//foreach
            //
            //
        }

        private void callback(UsageStatistic us)
        {
            lon.Add(new OldNew() { Old = us.clipName, New = "" });
            //CDBHandler.UpdateClipName("", "");
        }
        //===================================================================
    }//class
}//namespace
